package com.hjs.community.file.controller;

import com.community.common.core.utils.Result;
import com.community.common.security.dto.UserLoginDto;
import com.community.feign.contents.dto.UserDTO;
import com.community.feign.contents.user.UserFeign;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 *     头像上传
 * </p>
 *
 * @author lwl
 * @since 23-03-01
 */
@RestController
@RequestMapping("/file/")
public class FileUploadController {

    /**注入userFeign*/
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private UploadManager uploadManager;
    @Value("${community.ak}")
    private String accessKey;

    @Value("${community.sk}")
    private String secretKey;

    @Value("${community.bucket}")
    private String bucket;

    @Value("${community.host}")
    private String host;

    @PostMapping("upload")
    public Result upload(MultipartFile file, UserLoginDto userLoginDto) {

        String originalFilename = file.getOriginalFilename();

        String key = "weixin/"+originalFilename;
        System.out.println(userLoginDto);
        //1.通过七牛云ak和sk这个token上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //Response response = uploadManager.put(localFilePath, key, upToken);
            //2.解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

            //3.上传成功后调用修改的头像的方法
            UserDTO userDTO=new UserDTO();
            userDTO.setAvatar(host+key);
            userDTO.setId(userLoginDto.getUserId());
            System.out.println("userDto----》"+userDTO);
            userFeign.currentUserInfo(userDTO);


        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result().ViewOk(host+key);
    }


}
